import { getUserInfo } from "@/components/Login/api";
import { createDrawChannel, getAiConsumerPoint, getDrawChannels } from "@/api";

export type IUserInfo = {
    id?: number;
    username?: string;
    avatar?: string;
};
export interface IUserChannel { 
    id: number;
    name:string
}

export interface IUserStore {
    userInfo: IUserInfo;
    userDrawChannel: IUserChannel[];
    activeChannel: IUserChannel;
    pointNum: number;
    openPayModal: boolean;
    openLoginModal: boolean;
    setUserInfo: (value: IUserInfo) => void;
    setUserChannel: (value: IUserChannel[]) => void;
    addChannel: (name:string) => void;
    fetchUserInfo: (cb?: (res: IUserInfo) => void, ercb?: () => void) => void;
    featchUserDrawChannel: (cb?: (res: IUserChannel[]) => void) => void;
    setUserPoint: (point: number) => void;
    fetchUserPoint: () => void;
    changePayModalStatus: (status: boolean) => void;
    setOpenLoginModal: (status: boolean) => void;
}

const userStore = (): IUserStore => {
    return {
        userInfo: { id: 0, username: '', avatar: '' },
        userDrawChannel: [],
        activeChannel: {} as IUserChannel,
        pointNum: 0,
        openPayModal: false,
        openLoginModal: false,
        setOpenLoginModal(status) { 
            this.openLoginModal = status
        },
        changePayModalStatus: function (status) { 
            this.openPayModal = status
        },
        setUserInfo: function (value) {
            this.userInfo = value;
        },
        addChannel(name:string) {  
            createDrawChannel(name).then(res => { 
                console.log('-------createChannel res',res)
            })
        },
        setUserChannel: function (channels) {
            this.userDrawChannel = channels
            this.activeChannel = channels[0]
        },
        setUserPoint(point:number) { 
            this.pointNum = point
        },
        fetchUserPoint() { 
            // 消费点数
            getAiConsumerPoint().then(res => {
                this.setUserPoint(res?.data?.num as number)
            })
        },
        featchUserDrawChannel: function (cb) { 
            getDrawChannels().then(res => { 
                this.setUserChannel(res.data)
            })
        },
        fetchUserInfo: function (cb,ercb) { 
            getUserInfo().then(res => { 
                if (!res.id) { 
                    ercb && ercb()
                    return;
                }
                // 设置user Store里面的信息
                this.setUserInfo({
                    id: res.id,
                    username:res.username,
                    avatar: res.avatar
                })
                cb && cb({
                    id: res.id,
                    username:res.username,
                    avatar: res.avatar
                })
                
            })
        }
    };
};

export default userStore;
